package com.infodeli.admin.service.impl;

import com.infodeli.admin.entity.InfoAttrValueEntity;
import com.infodeli.admin.entity.InfoCommentEntity;
import com.infodeli.admin.entity.InfoImagesEntity;
import com.infodeli.admin.service.InfoAttrValueService;
import com.infodeli.admin.service.InfoImagesService;
import com.infodeli.admin.vo.InfoAttrValueVo;
import com.infodeli.admin.vo.InfoAttrVo;
import com.infodeli.admin.vo.InfoVo;
import com.infodeli.common.utils.ComTool;
import com.infodeli.user.login.entity.UserEntity;
import com.infodeli.user.login.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infodeli.common.utils.PageUtils;
import com.infodeli.common.utils.Query;

import com.infodeli.admin.dao.InfoDao;
import com.infodeli.admin.entity.InfoEntity;
import com.infodeli.admin.service.InfoService;


@Service("infoService")
public class InfoServiceImpl extends ServiceImpl<InfoDao, InfoEntity> implements InfoService {

    @Autowired
    InfoAttrValueService infoAttrValueService;

    @Autowired
    InfoImagesService infoImagesService;

    @Autowired
    UserService userService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<InfoEntity> page = this.page(
                new Query<InfoEntity>().getPage(params),
                new QueryWrapper<InfoEntity>()
        );

        return new PageUtils(page);
    }

    public PageUtils queryPageToGetInfoIds(Map<String, Object> params, QueryWrapper<InfoEntity> wrapper) {
        IPage<InfoEntity> page = this.page(
                new Query<InfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 更新 info_status
     */
    @Override
    public void updateInfoStatus(List<InfoVo> infoVos) {
        List<InfoEntity> infoEntities = infoVos.stream().map(infoVo -> {
            InfoEntity entity = new InfoEntity();
            entity.setInfoId(infoVo.getInfoId());
            entity.setInfoStatus(infoVo.getInfoStatus());
            return entity;
        }).collect(Collectors.toList());
        this.updateBatchById(infoEntities);
    }

    @Override // 用户 更新 InfoVo
    public void updateVo(InfoVo info) {
        List<InfoImagesEntity> images = new ArrayList<>();
        List<InfoAttrValueEntity> values = new ArrayList<>();
        for(InfoAttrValueVo vo : info.getInfoAttrValueVos()){
            // 1、处理图片
            if(vo.getType() != null && "upload".equals(vo.getType())){
                // 1.1、删除原先的图片
                infoImagesService.remove(new QueryWrapper<InfoImagesEntity>().eq("info_id", info.getInfoId()));
                // 1.2、添加新的图片
                if(vo.getAttrValue() == null || "".equals(vo.getAttrValue())){

                }else{
                    String[] split = vo.getAttrValue().split(";");
                    for(int i = 0;i<split.length;i++){
                        InfoImagesEntity image = new InfoImagesEntity();
                        image.setInfoId(info.getInfoId());
                        image.setImgSort(i);
                        image.setImgUrl(split[i]);
                        if(i == 0){
                            image.setDefaultImg(1);
                        }else{
                            image.setDefaultImg(0);
                        }
                        images.add(image);
                    }
                    infoImagesService.saveBatch(images);
                }

            }else{
                // 2.1、收集其他属性值
                InfoAttrValueEntity value = new InfoAttrValueEntity();
                value.setValId(vo.getValId());
                value.setAttrValue(vo.getAttrValue());
                values.add(value);
            }
        }
        // 2.2、修改其他属性值
        infoAttrValueService.updateBatchById(values);
        // 3、修改信息基本内容
        InfoEntity updateInfo = new InfoEntity();
        updateInfo.setInfoId(info.getInfoId());
        updateInfo.setInfoTitle(info.getInfoTitle());
        updateInfo.setInfoStatus(1);
        if(images.size()>0){
            updateInfo.setInfoDefaultImg(images.get(0).getImgUrl());
        }else{
            updateInfo.setInfoDefaultImg("");
        }
        this.updateById(updateInfo);


    }

    @Override
    public void addCommentNum(Long infoId, Integer num) {
        baseMapper.addCommentNum(infoId, num);
    }




    /**
     * 全部分页查询
     * info_status：[0-待,1-审核,2-成功,-1-删,-2-失败]
     *
     * 管理员：
     *      查看审核信息 1
     *      查看所有信息
     *      种类查看 info_id
     *
     * 用户：
     *      其他用户的正常信息 user_id 2
     *      其他用户的正常信息 种类 user_id cat_id 2
     *      我的全部信息 user_id
     *      我的待审核信息
     *
     * 总结： infoStatus数组、user_id、cat_id、关键字
     *
     *
     */
    /*
{
    "page":{
        "key":"威海",
        "limit": "6"
    },
    "infoStatus":[1,2,0,-1], //[0-待,1-审核,2-成功,-1-删,-2-失败]
    "userId": "1",
    "useUserId": "1",
    "catId": "5"
}
    * */
    @Override
    public PageUtils queryPageVo(Map<String, Object> params){
        QueryWrapper<InfoEntity> wrapper = getQueryWrapper(params);

        // key 关键字
        Map<String, Object> map = new HashMap<>();
        if(params.get("page") != null) {
            map = ((Map<String, Object>) params.get("page"));
        }
        // 1、先分页 查出对应的 信息id
        PageUtils pageUtils = this.queryPageToGetInfoIds(map, wrapper);
        List<Long> infoIds = pageUtils.getList().stream().map(entity -> {
            return ((InfoEntity) entity).getInfoId();
        }).collect(Collectors.toList());

        if(infoIds == null || infoIds.size() == 0){
            pageUtils.setList(null);
        }else{
            // 2、查询这些 信息id 对应的内容，直接查询，无需分页
            List<InfoVo> infoVos = this.baseMapper.queryPageVo(new QueryWrapper<InfoEntity>().in("info.info_id", infoIds));
            pageUtils.setList(infoVos);
            Collections.sort(pageUtils.getList(), (n1, n2)->{
                return -( ((InfoVo)n1).getCreateTime().compareTo( ((InfoVo)n2).getCreateTime() ));
            });
        }



        return pageUtils;
    }

    @Override
    public InfoVo getVoById(Long infoId) {
        QueryWrapper<InfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("info.info_id", infoId);
        InfoVo vo = this.baseMapper.getVoForUpdate(wrapper);
        Collections.sort(vo.getInfoAttrValueVos(), (n1, n2) ->{
            return (n1.getSort() - n2.getSort());
        });

        return vo;
    }

    @Override // 之前写的，对每一个表都进行查询，没有进行表的关联操作【废弃】
    public PageUtils queryPage1(Map<String, Object> params) {
        QueryWrapper<InfoEntity> wrapper = getQueryWrapper(params);

        // key 关键字
        Map<String, Object> map = new HashMap<>();
        if(params.get("page") != null) {
            map = ((Map<String, Object>) params.get("page"));
        }

        System.out.println("debug......");



        IPage<InfoEntity> page = this.page(
                new Query<InfoEntity>().getPage(map),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<?> list = pageUtils.getList();


        // 获取infoVo集合
        List<InfoVo> infoVos = getInfoVos(list);

        pageUtils.setList(infoVos);

        return pageUtils;
    }

    public QueryWrapper<InfoEntity> getQueryWrapper(Map<String, Object> params){
        QueryWrapper<InfoEntity> wrapper = new QueryWrapper<>();
        // infoStatus 信息状态
        if(params.get("infoStatus") != null){
            List<Integer> infoStatus = (ArrayList<Integer>)params.get("infoStatus");
            if(infoStatus != null && infoStatus.size() != 0){
                wrapper.in("info_status", infoStatus);
            }
        }
        // userId 用户id
        if(params.get("userId") != null && !"".equals((String) params.get("userId"))) {
            Long userId = Long.parseLong((String) params.get("userId"));
            // 这里还需要考虑 是用 还是不用
            if(params.get("useUserId") != null ){
                Integer useUserId = Integer.parseInt((String) params.get("useUserId"));
                if(useUserId == 1){ // 1，仅查询该用户
                    wrapper.eq("user_id", userId);
                }else if(useUserId == -1){ // 2，不查询该用户
                    wrapper.ne("user_id", userId);
                }else if(useUserId == 0){
                    // 查询 所有用户
                }
            }
        }
        // catId 种类id【种类查找】
        if(params.get("catId")!= null && !"".equals((String) params.get("catId"))) {
            Long catId = Long.parseLong((String) params.get("catId"));
            if(catId != 0){
                wrapper.eq("cat_id", catId);
            }
        }
        // key 关键字
        Map<String, Object> map = new HashMap<>();
        if(params.get("page") != null) {
            map = ((Map<String, Object>) params.get("page"));
            if(map.get("key") != null){
                String key = (String) (map.get("key"));
                if(key != null && !"".equals(key)) {
                    wrapper.like("info_title", key);
                }
            }
        }

        System.out.println("debug......");
        return wrapper;
    }

    /** 根据 infoEntity集合 获取 infoVo集合 */
    public List<InfoVo> getInfoVos(List<?> list){
        List<InfoVo> infoVos = list.stream().map(entity -> {
            // 对于每一个 infoEntity 对象
            InfoVo infoVo = new InfoVo();
            BeanUtils.copyProperties(entity, infoVo);
            // 2、获取 info_attr_value;
            List<InfoAttrValueEntity> infoAttrValueEntities = infoAttrValueService.list(
                    new QueryWrapper<InfoAttrValueEntity>().eq("info_id", ((InfoEntity) entity).getInfoId()));
            List<InfoAttrValueVo> infoAttrValueVos = infoAttrValueEntities.stream().map((entity1) -> {
                InfoAttrValueVo vo1 = new InfoAttrValueVo();
                BeanUtils.copyProperties(entity1, vo1);
                return vo1;
            }).collect(Collectors.toList());
            // 3、获取 infoAttrVo 同时 处理image
            /*
            for(InfoAttrValueEntity valueEntity : infoAttrValueEntities){
                if ("upload".equals(valueEntity.getType())) {
                    List<InfoImagesEntity> infoImagesEntities = infoImagesService.list(
                            new QueryWrapper<InfoImagesEntity>().eq("info_id", ((InfoEntity) entity).getInfoId()));
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < infoImagesEntities.size(); i++) {
                        if (i == 0) {
                            sb.append(infoImagesEntities.get(i).getImgUrl());
                            ((InfoEntity) entity).setInfoDefaultImg(infoImagesEntities.get(i).getImgUrl());
                        } else {
                            sb.append(';').append(infoImagesEntities.get(i).getImgUrl());
                        }
                    }
                    valueEntity.setAttrValue(sb.toString());
                }
            }*/
            List<InfoImagesEntity> infoImagesEntities = infoImagesService.list(
                    new QueryWrapper<InfoImagesEntity>().eq("info_id", ((InfoEntity) entity).getInfoId()));
            if(infoImagesEntities != null && infoImagesEntities.size() != 0){
                List<String> img = infoImagesEntities.stream().sorted((img1, img2) -> {
                    return img1.getImgSort() - img2.getImgSort();
                }).map(image -> {
                    return image.getImgUrl();
                }).collect(Collectors.toList());
                infoVo.setImg(img);
            }else{
                infoVo.setImg(new ArrayList<String>());
            }

            infoVo.setInfoAttrValueVos(infoAttrValueVos);


            // 4、处理 上传者信息
            UserEntity user = userService.getById(((InfoEntity) entity).getUserId());
            infoVo.setNickName(user.getNickName());
            infoVo.setPortrait(user.getPortrait());

            return infoVo;
        }).collect(Collectors.toList());

        return infoVos;
    }



    /**
     * 将 用户上传的信息 保存到 数据库中
     * 向 info、info_attr_vale、info_image 表添加数据
     */
    @Override
    public void userSave(InfoVo vo, Long uid) {
        vo.setUserId(uid); // 添加 用户id

        // 2、向 info_attr_value 表【当遇到图片时，收集图片，在收集图片过程中，为info添加默认图片】
        doUserSave(vo);
    }

    // 保存：整体上处理 attrValue，细节上遇到 图片 后，单独进行处理
    public void doUserSave(InfoVo vo){
        List<InfoAttrVo> infoAttrVos = vo.getInfoAttrVos();
        List<InfoAttrValueEntity> infoAttrValueEntities = new ArrayList<>(); // info_attr_value
        List<InfoImagesEntity> infoImagesEntities = null; // info_image
        for(InfoAttrVo infoAttrVo : infoAttrVos) {
            if (!"upload".equals(infoAttrVo.getType())) {
                InfoAttrValueEntity entity = new InfoAttrValueEntity();
                // entity.setInfoId(vo.getInfoId()); // 因为还没有插入info，所以不知道infoId
                entity.setAttrId(infoAttrVo.getAttrId());
                entity.setAttrName(infoAttrVo.getAttrName());
                entity.setType(infoAttrVo.getType());
                infoAttrValueEntities.add(entity);
                entity.setAttrValue(infoAttrVo.getAttrValue());
            } else {
                // 对于图片，保存在单独的 信息图片表中
                infoImagesEntities = getInfoImagesEntities(vo, infoAttrVo);
            }
        }

        // 1、向 info 表
        InfoEntity info = getInfo(vo);
        this.save(info);
        vo.setInfoId(info.getInfoId());
        System.out.println("数据库中"+info);
        System.out.println("原数据"+vo);


        // 2、向 info_attr_value 表
        for(InfoAttrValueEntity entity: infoAttrValueEntities){
            entity.setInfoId(vo.getInfoId());
        }
        infoAttrValueService.saveBatch(infoAttrValueEntities);


        // 3、向 images 表
        if (infoImagesEntities != null && infoImagesEntities.size() != 0) {
            for(InfoImagesEntity entity : infoImagesEntities){
                entity.setInfoId(vo.getInfoId());
            }
            infoImagesService.saveBatch(infoImagesEntities);
        }

    }
    // 保存： info
    public InfoEntity getInfo(InfoVo vo){
        InfoEntity info =  new InfoEntity();
        vo.setCreateTime(ComTool.getDateStr());
        BeanUtils.copyProperties(vo, info);
        info.setAnon(0);
        info.setCommentNum(0);
        if(info.getInfoDefaultImg() == null){
            info.setInfoDefaultImg("");
        }
        return info;
    }

    // 保存：获取 图片img，设置 默认图片
    public List<InfoImagesEntity> getInfoImagesEntities(InfoVo vo, InfoAttrVo infoAttrVo){
        if(infoAttrVo.getAttrValue() == null || "".equals(infoAttrVo.getAttrValue())){
            // 无需插入图片
            vo.setInfoDefaultImg("");
            return null;
        }
        List<InfoImagesEntity> infoImagesEntities = new ArrayList<>();
        String[] urls = infoAttrVo.getAttrValue().split(";");
        for(int i = 0;i< urls.length;i++){
            InfoImagesEntity image = new InfoImagesEntity();
            // image.setInfoId(vo.getInfoId()); // 因为还没有插入info，所以不知道infoId
            image.setImgUrl(urls[i]);
            image.setImgSort(i);
            if(i == 0){
                image.setDefaultImg(1);
                vo.setInfoDefaultImg(urls[i]);
            }else{
                image.setDefaultImg(0);
            }
            infoImagesEntities.add(image);
        }
        return infoImagesEntities;
    }

}